﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using QD.Utill;
using QD.Snapshot.Core.Config;
using NSoup.Nodes;
using NSoup.Select;

namespace QD.Snapshot.Core.BLL
{
    public class Search_Bing : SearchBase
    {
        public Search_Bing(TextBox textBox, int SleepTime)
        {
            this.textBox = textBox;
            this.SleepTime = SleepTime;
            this.copyform = "3";        //Bing搜索
            Echo("Bing截图已启动");
        }

        HttpRequest Http = new HttpRequest();
        Model.TaskModel_360 taskModel = new Model.TaskModel_360();
        public override void Search(string keyword, Model.Product product, Model.WebSite company)
        {
            Thread.Sleep(SleepTime);

            Http.ClearCookie();
            Http.AddCookie("MUID", "11B585304B52619925A689FA4A7C60C6", ".bing.com", DateTime.Now.AddDays(180));
            var obj = Http.RequsetObj(string.Format(Engine.URL_Bing, keyword));

            IsCode_Bing = CheckCode(obj.Html);   //是否出现验证码

            if (IsCode_Bing)
            {
                EchoCodeLog(EngineType.Bing, "Bing出现验证码");
                Thread.Sleep(1000);
            }
            else if (obj.ErrorMessage.Length > 0)
            {
                Echo(string.Format("搜索 {0} 返回错误:{1}", keyword, obj.ErrorMessage));
            }
            else if (obj.Code >= 300 && obj.Code < 400)
            {
                EchoLog("code", "Bing搜索频繁");
            }
            else
            {
                Echo(string.Format("搜索 {0}", keyword));
            }
            taskModel.itemid = product.itemid;
            taskModel.keyword = keyword;
            taskModel.company = company;
            taskModel.html = obj.Html;

            NumHelper.Instance.SetNumBing(1);    //统计搜索速度
            ThreadPool.QueueUserWorkItem(new WaitCallback(CheckOrAdd), taskModel);
        }

        void CheckOrAdd(object obj)
        {
            Model.TaskModel_360 model = obj as Model.TaskModel_360;

            CheckOrAdd(model.html, model.keyword, model.itemid, model.company);
        }

        void CheckOrAdd(string html, string keyword, int itemid, Model.WebSite company)
        {
            NSoup.Nodes.Document doc = NSoup.NSoupClient.Parse(html);
            Regex r1 = new Regex(FixRegex(company.ShortName), RegexOptions.IgnoreCase);
            Regex SiteName = new Regex(FixRegex(company.SiteName), RegexOptions.IgnoreCase);
            Regex Cellphone = new Regex(FixRegex(company.Cellphone), RegexOptions.IgnoreCase);
            Regex phone = new Regex(FixRegex(company.Phone), RegexOptions.IgnoreCase);

            CheckOrAdd(doc, r1, SiteName, Cellphone, phone, itemid, company.UserID, keyword);
        }

        private readonly object obj = new object();
        Model.Snap snapModel = new Model.Snap();
        void CheckOrAdd(Document doc, Regex r1, Regex SiteName, Regex Cellphone, Regex phone, int itemid, int userid, string keyword, int page = 1)
        {
            Element parent = doc.GetElementById("b_results");
            if (parent == null) return;

            HideElement(doc.GetElementById("b_context"));           //清除右侧         
            HideElementList(parent.GetElementsByClass("b_ad"));     //清除 广告
            HideElementList(parent.GetElementsByClass("b_ans"));    //清除推荐图片、电影、词典、3C

            Elements result = parent.Select(".b_algo");

            int index = 0;
            bool isFirst = true;
            string nums_html = "";

            foreach (Element ele in result)
            {
                index++;

                if (r1.IsMatch(ele.Text()) || CheckShortNameList(ele.Text()) || CheckQJY(ele.Text(), SiteName, Cellphone, phone))
                {
                    string index_key = GetMd5(ele.GetElementsByTag("h2").Text); //第几行的key,更新时，用来确定更新哪一行
                    string platform = GetPlatform(ele.Text());                  //上词的平台

                    if (isFirst)
                    {
                        RemoveAttr(result);
                        nums_html = "<span id='sp_nums' class='sp_nums' data='" + doc.Select("#b_tween .sb_count").Text + "'></span>";
                        isFirst = false;
                    }

                    //添加成功记录
                    lock (obj)
                    {
                        snapModel.itemid = itemid;
                        snapModel.userid = userid;
                        snapModel.keyword = keyword;
                        snapModel.ranking = index;
                        snapModel.copyform = Convert.ToInt32(copyform);
                        snapModel.page = page;
                        snapModel.state = 0;
                        snapModel.clientid = SiteConfig.ClientId;
                        snapModel.platform = platform;
                        snapModel.updatetime = DateTime.Now;
                        snapModel.index_key = index_key;
                        snapModel.html = result.OuterHtml() + nums_html;
                        AddSnap(snapModel);
                        BLL.File.Snap.AddSnap(snapModel);
                    }
                }
            }
        }

        protected override void RemoveAttr(Elements result)
        {
            Elements div = result.Select("div");
            div.RemoveAttr("u");

            Elements ele = result.Select("a");
            ele.Attr("href", "#");
            ele.RemoveAttr("target");
            ele.RemoveAttr("name");
            ele.RemoveAttr("aria-haspopup");
            ele.RemoveAttr("aria-label");
            ele.RemoveAttr("h");

            Elements span = result.Select("span");
            span.RemoveAttr("h");
            span.RemoveAttr("k");
        }
    }
}